import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:sp_util/sp_util.dart';
import 'package:tuple/tuple.dart';
import 'package:yp/config/config.dart';

// import 'package:yp/pages/main/logic.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import '../../../helper.dart';
import '../../../router.dart';
import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class GoodsDetailLogic extends GetxController {
  // String itemNumId = goodsJson['default_item_num_id'].toString();
  //       String styleNumId = goodsJson['style_num_id'].toString();
  //       String shopId = goodsJson['shop_num_id'].toString();
  //       String cat1Id = goodsJson['cat1_id'].toString();
  //       String ecStyleNumId = goodsJson['ec_style_num_id'].toString();
  //       Get.toNamed(RouteConfig.goodsDetail, arguments: {
  //         'itemNumId': itemNumId,
  //         'styleNumId': styleNumId,
  //         'shopId': shopId,
  //         'cat1Id': cat1Id,
  //         'ecStyleNumId': ecStyleNumId,
  //       });
  String itemNumId;
  String styleNumId;
  String shopId;
  String cat1Id;
  String ecStyleNumId;

  // final MainAppLogic mainAppLogics = Get.put(MainAppLogic());
  // final MainLogic mainLogic = Get.put(MainLogic());
  final GoodsDetailState state = GoodsDetailState();

  @override
  void onInit() {
    super.onInit();

    getAdvertisingList();
    try {
      if (Get.arguments != null) {
        state.styleNumId = Get.arguments['styleNumId'];
        // state.startTime = Get.arguments['to_start'];
        state.shopId = Get.arguments['shopId'];
        // state.typeIndex = Get.arguments['typeIndex'] is String
        //     ? int.parse(Get.arguments['typeIndex'])
        //     : Get.arguments['typeIndex'] ?? 0;
      } else {
        // state.typeIndex = int.parse(getQueryVariable('typeIndex') ?? '0');
        // if (SpUtil.getInt('empeNumId') == 0 ||
        //     SpUtil.getInt('empeNumId') == null) {
        //   Get.offAllNamed(RouteConfig.mallLogin, arguments: arguments);
        //   return;
        // }
      }
    } catch (e) {}
    state.typeIndex = Get.arguments['typeIndex'] is String
        ? int.parse(Get.arguments['typeIndex'])
        : Get.arguments['typeIndex'] ?? 0;
    update();
  }

  // 获取广告
  void getAdvertisingList() {
    var params = {
      'adv_category': 2,
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      print("广告：$event");
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
      } else {
        state.advertising = [];
      }
      update();
    });
  }

  void requestDetail() async {
    getAndGoThirdShop();
    keFu();
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "style_num_id": styleNumId,
      "shop_id": shopId,
      "item_num_id": itemNumId,
      // "access_token": SpUtil.getString('token'),
      "access_token": '',

      "prv_num_id": state.addressInfo['prv_num_id'],
      "city_num_id": state.addressInfo['city_num_id'],
      "city_area_num_id": state.addressInfo['city_area_num_id'],
      "town_num_id": state.addressInfo['town_num_id'],
      "maplocation_x": state.addressInfo['maplocation_x'],
      "maplocation_y": state.addressInfo['maplocation_y'],

      // "user_num_id": SpUtil.getInt('empeNumId'),
      "user_num_id": 0,
      'customer_type': 3,
    };

    LogUtil.d("++++++++goodsDetail参数+++++$params");
    Api.goodsDetail(params).listen((event) {
      LogUtil.d("++++++++goodsDetail+++++$event");
      if (event["code"] == 0) {
        state.isShowDetail = true;
        update();
        state.goodsDetail = event;
        cat1Id = event['cat1_id']?.toString() ?? '';
        ecStyleNumId = event['spec_item_detail'] != null
            ? '${event['spec_item_detail']['ec_style_num_id']}'
            : '';
        state.deliveryType = event["delivery_type"];

        getAdvertisingList();
        requestRecommendGoods();
        requestComment();
        requestImageAndContent();
        promotionalInformation();
        specificationParameters();

        int shopId = event['shop_id'];
        int styleNumId = event['spec_item_detail'] != null
            ? event['spec_item_detail']['style_num_id']
            : null;
        var params11 = {
          "sql_id": "MDMS-STYLE-EXTEND-ITEM",
          "input_param": {
            "ec_shop_num_id": shopId,
            "style_num_id": styleNumId,
          }
        };

        Api.workCexport(params11).listen((event) {
          if (event['code'] == 0) {
            state.showhou = event['results'][0];
            update();
          }
        });

        if (SpUtil.getString('token') != null &&
            SpUtil.getString('token').isNotEmpty) {
          requestAvailableCoupons();
          whetherCollection();
        }
      } else {
        state.isShowDetail = false;
      }
      update();
    });
    getConsume();
  }

  // 商品详情
  void enterGoodsDetail(style_num_id, ec_style_num_id, cat_id,
      default_item_num_id, shop_num_id, is_pre_sale) {
    String itemNumId = default_item_num_id.toString();
    String styleNumId = style_num_id.toString();
    String ecStyleNumId = ec_style_num_id.toString();
    Get.toNamed(RouteConfig.goodsDetail, arguments: {
      'itemNumId': itemNumId,
      'styleNumId': styleNumId,
      'shopId': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'].toString(),
      'ecStyleNumId': ecStyleNumId,
      'typeIndex': is_pre_sale,
    });
  }

  // 获取客服信息
  void keFu() {
    print('获取客服信息 ======== 获取客服信息11111111');
    Api.MaterialGoodsSelect1({"config_name": "platform_ec_shop_num_id"})
        .listen((event) {
      print('获取客服信息 ======== 获取客服信息 ********  event = $event');
      var configValue = event["config_value"];
      Api.getAccessID(configValue.toString()).listen((event) {
        print('获取客服信息 ======== 获取客服信息  event = $event');
        // state.accessID = event["access_id"];
        state.keFuString = event['access_id'];
        update();
      });
    });
  }

  // 获取是否收藏
  void whetherCollection() {
    var params = {
      "access_token": SpUtil.getString('token'),
      'style_num_id': styleNumId,
      'ec_shop_num_id': shopId
    };
    Api.whetherCollection(params).listen((event) {
      print('获取是否收藏  =============== event = $event');
      if (event['code'] == 0) {
        state.favorite_sign = event['favorite_sign'];
      }
      update();
    });
  }

  // 促销信息
  void promotionalInformation() {
    var params = {
      'shop_id': shopId,
      'super_ec_shop_num_id':
          SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']?.toString(),
      // 'vip_type_num_id': '',
      'item_num_id_list': ['$styleNumId'],
    };
    // var params = {
    //   "use_platform": 2,
    //   "shop_id": shopId,
    //   "access_token": SpUtil.getString('token'),
    //   // "super_ec_shop_num_id": SpUtil.getInt('storeShopNum')?.toString(),
    //   'head_ec_shop_num_id':
    //       SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']?.toString(),
    //   "channel_num_id": 99,
    //   "item_num_id_list": [itemNumId],
    //   "promotion_tag_list": []
    // };
    Api.promotionalInformation(params).listen((event) {
      print('============= 促销信息 ===========  event = $event');
      if (event['code'] == 0) {
        List list = event['tag_list'];
        if (list.length > 0) {
          Map map = list[0];
          state.promotionalInformationList = map['norm_tag_models'];
        }
      }
      update();
    });
  }

  // 规格参数
  void specificationParameters() {
    print('+++++++++++++++++++++++  itemNumId = $itemNumId');
    var params = {
      // "data_sign": 0,
      // "channel_num_id": 99,
      // "use_platform": 2,
      "style_num_id": styleNumId,
      "shop_id": shopId,
      "prv_num_id": state.addressInfo['prv_num_id'],
      "city_num_id": state.addressInfo['city_num_id'],
      "city_area_num_id": state.addressInfo['city_area_num_id'],
      "town_num_id": state.addressInfo['town_num_id'],
      "maplocation_x": state.addressInfo['maplocation_x'],
      "maplocation_y": state.addressInfo['maplocation_y'],
      "access_token": SpUtil.getString('token'),
      "use_platform": Config.env == 3 ? 1 : 2,
      "range_type": 1,
    };
    Api.specificationParameters(params).listen((event) {
      print('====================  规格参数 返回数据   event = $event');
      if (event['code'] == 0) {
        if (event['style'] != null) {
          if (event['style']['spec'] != null) {
            state.spec_item = event['style']['spec']['spec_item'];
            update();
            if (event['style']['spec']['specs'] != null) {
              if (event['style']['spec']['specs']['specs'] != null) {
                List list = event['style']['spec']['specs']['specs'];
                print('+++++++++++++++规格参数 返回数据++++  list = $list');
                state.specificationParametersList = list;
                state.specificationParameters =
                    event['style']['spec']['spec_item'];
                list.forEach((element) {
                  Map map = element;
                  List list = map['spec_values'];
                  if (list.length > 0) {
                    state.chooseSpecificationsList.add(list[0]);
                  }
                  state.specName =
                      state.chooseSpecificationsList[0]['spec_value'];
                  state.ec_style_num_id = list[0]['spec_value_id'];
                });

                /// 生成默认规格信息
                state.ecStyleNumIdList =
                    List.generate(list.length, (index) => 0);
                for (var i = 0; i < list.length; i++) {
                  state.ecStyleNumIdList[i] =
                      list[i]['spec_values'][0]['spec_value_id'];
                }

                print(">>>>>>>ecStyleNumIdList=${state.ecStyleNumIdList}");
              }
            }
          }
        }
      }
      update();
    });
  }

  // 推荐商品
  void requestRecommendGoods() {
    var token = SpUtil.getString('token');
    if (token == null || token == '') return;
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "cat1_id": cat1Id,
      "is_recommend": 1,
      "shop_id": shopId,
      "shop_num_id": shopId,
      "prv_num_id": state.addressInfo['prv_num_id'],
      "city_num_id": state.addressInfo['city_num_id'],
      "city_area_num_id": state.addressInfo['city_area_num_id'],
      "town_num_id": state.addressInfo['town_num_id'],
      "maplocation_x": state.addressInfo['maplocation_x'],
      "maplocation_y": state.addressInfo['maplocation_y'],
      "page_no": 1,
      "page_size": 10,
      "access_token": SpUtil.getString('token')
    };
    Api.recommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        state.recommendGoods = event;
        update();
      }
    });
  }

  // 商品规格信息
  void requestImageAndContent() {
    var params = {
      "use_platform": 2,
      "ec_style_num_id": ecStyleNumId,
      "type": "wap"
    };
    Api.goodsDetailImageAndContent(params).listen((event) {
      if (event['code'] == 0) {
        state.richText = event;
        update();
      }
    });
  }

  void requestGotCoupons(Function callback) {
    var params = {
      'use_platform': 2,
      'access_token': SpUtil.getString('token'),
      'status': '1',
      'page': 1,
      'rows': 50,
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };
    Api.availableCouponsList(params).listen((event) {
      if (event['code'] == 0) {
        state.gotCoupons = event;
        callback.call();
      }
    });
  }

  void requestAvailableCoupons() {
    var userParams = {
      'access_token': SpUtil.getString('token'), // token
      'mobile': SpUtil.getString('number'),
    };
    Api.searchMember(userParams).listen((event) {
      //会员查询接口
      if (event['code'] == 0) {
        String vipTypeNumId = event['vip_type_num_id'].toString();
        var params = {
          "use_platform": 2,
          "item_num_id": itemNumId,
          "sub_unit_num_id": shopId,
          "vip_type_num_id": vipTypeNumId,
          "access_token": SpUtil.getString('token')
        };
        Api.centerCouponsList(params).listen((event) {
          // 领券中心
          if (event['code'] == 0) {
            state.availableCoupons = event;
            update();
          }
        });
      }
    });
  }

  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId,
      {int quantity = 1}) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": state.num,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": state.ec_style_num_id == null
          ? state.goodsDetail['spec_item_detail']['ec_style_num_id']
          : state.ec_style_num_id,
      'access_token': SpUtil.getString('token'),
    };

    if (state.ec_style_num_id != null) {
      // var itemId = "";
      var key = "${state.ec_style_num_id}";
      // print(state.goodsDetail);
      // return;
      key = state.ecStyleNumIdList.join("_");
      if (state.spec_item[key] == null) {
        toast("当前规格无货");
        return;
      }
      params["item_num_id"] = state.spec_item[key]["item_num_id"];
    }

    print(params);
    // return;

    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        // mainLogic.getCartNum();
        toast('加入购物车成功');
      } else {
        toast(event['message']);
      }
    });
  }

  // 商品评论列表
  void requestComment() {
    var params = {
      "use_platform": 2,
      "page_no": 1,
      "page_size": 1,
      "style_num_id": styleNumId,
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "traderate_sign": 1 //0默认返回列表，1返回推荐好评的一条
    };
    Api.goodsComments(params).listen((event) {
      if (event['code'] == 0) {
        state.comment = event;
        update();
      }
    });
  }

  void shareToFriend() {
    // if (state.goodsDetail['spec_item_detail'] == null ||
    //     state.goodsDetail['spec_item_detail']['image_default_id'] == null ||
    //     state.goodsDetail['spec_item_detail']['image_default_id'] == '') {
    //   toast("分享失败，未获取到图片地址");
    //   return;
    // }
    int isPreSale = state.goodsDetail['spec_item_detail']['is_pre_sale'];

    var data;
    // if (isPreSale == 1) {
    //   data =
    //       '/pages/index?currentShopId=${SpUtil.getInt('storeShopNum')?.toString()}&mberType=2&applyerId=${SpUtil.getInt('empeNumId')}&otherguide=false&isGopreSale=1&style_num_id=${state.goodsDetail['style_num_id']}&itemid=${state.goodsDetail['item_num_id']}';
    // } else {
    //   data =
    //       '/pages/index?currentShopId=${SpUtil.getInt('storeShopNum')?.toString()}&mberType=2&applyerId=${SpUtil.getInt('empeNumId')}&otherguide=false&isGoGoodDetail=true&style_num_id=${state.goodsDetail['style_num_id']}&itemid=${state.goodsDetail['item_num_id']}';
    // }
    if (isPreSale == 1) {
      data =
          '/pages/index?currentShopId=${state.goodsDetail['shop_id']}&mberType=2&applyerId=${SpUtil.getInt('empeNumId')}&applyer=${SpUtil.getInt('empeNumId')}&otherguide=false&isGopreSale=1&style_num_id=${state.goodsDetail['style_num_id']}&itemid=${state.goodsDetail['item_num_id']}';
    } else {
      data =
          '/pages/index?currentShopId=${state.goodsDetail['shop_id']}&mberType=2&applyerId=${SpUtil.getInt('empeNumId')}&applyer=${SpUtil.getInt('empeNumId')}&otherguide=false&isGoGoodDetail=true&style_num_id=${state.goodsDetail['style_num_id']}&itemid=${state.goodsDetail['item_num_id']}';
    }

    if (state.goodsDetail['spec_item_detail'] == null ||
        state.goodsDetail['spec_item_detail']['image_default_id'] == null ||
        state.goodsDetail['spec_item_detail']['image_default_id'] == '') {
      var model = new WeChatShareMiniProgramModel(
        path: data,
        webPageUrl: 'www.baidu.com',
        userName: Config.MINI_ACCOUNT,
        // miniProgramType: WXMiniProgramType.RELEASE,
        miniProgramType:
            Config.isDev ? WXMiniProgramType.TEST : WXMiniProgramType.RELEASE,
        title: state.goodsDetail['title'],
        description: state.goodsDetail['title'],
        // title: state.goodsDetail['spec_item_detail']['item_name'],
        // description: state.goodsDetail['spec_item_detail']['item_name'],
        // thumbnail: WeChatImage.network(
        //   goodsImage,
        // ),
        thumbnail: WeChatImage.asset(
          'assets/images/defaultAvatar_image.png',
        ),
      );
      fluwx.shareToWeChat(model);
    } else {
      String goodsImage =
          state.goodsDetail['spec_item_detail']['image_default_id'];
      var model = new WeChatShareMiniProgramModel(
        path: data,
        webPageUrl: 'www.baidu.com',
        userName: Config.MINI_ACCOUNT,
        // miniProgramType: WXMiniProgramType.RELEASE,
        miniProgramType:
            Config.isDev ? WXMiniProgramType.TEST : WXMiniProgramType.RELEASE,
        title: state.goodsDetail['title'],
        description: state.goodsDetail['title'],
        // title: state.goodsDetail['spec_item_detail']['item_name'],
        // description: state.goodsDetail['spec_item_detail']['item_name'],
        thumbnail: WeChatImage.network(
          goodsImage,
        ),
      );
      fluwx.shareToWeChat(model);
    }
  }

  void requestPosterData(var goodsDetail, Function(String qrCode) callback) {
    var data;

    int isPreSale = goodsDetail['spec_item_detail'] != null
        ? goodsDetail['spec_item_detail']['is_pre_sale']
        : null;
    int shopId = goodsDetail['shop_id'];
    int styleNumId = goodsDetail['spec_item_detail'] != null
        ? goodsDetail['spec_item_detail']['style_num_id']
        : null;
    int itemNumId = goodsDetail['spec_item_detail'] != null
        ? goodsDetail['spec_item_detail']['item_num_id']
        : null;
    if (isPreSale == 1) {
      data = {
        "currentShopId": "$shopId",
        "mberType": 2,
        "applyerId": "${SpUtil.getInt('empeNumId')}",
        "otherguide": false,
        "isGopreSale": 1,
        "style_num_id": "$styleNumId",
        "itemid": "$itemNumId",
        "applyer": SpUtil.getInt('empeNumId'),
      };
    } else {
      data = {
        "currentShopId": "$shopId",
        "mberType": 2,
        "applyerId": "${SpUtil.getInt('empeNumId')}",
        "otherguide": false,
        "isGoGoodDetail": true,
        "style_num_id": "$styleNumId",
        "itemid": "$itemNumId",
        "applyer": SpUtil.getInt('empeNumId'),
      };
    }
    var params = {
      "qrcode_media_type": 2,
      "qrcode_type": 0,
      "content": null,
      "miniprogram_code": {
        "appid": Config.MINI_APPID,
        "scene": "",
        "page": "pages/index"
      },
      "related_entity_id": "$styleNumId",
      "valid_type": 1,
      "valid_length": null,
      "applyer": SpUtil.getInt('empeNumId'),
      "datajson": jsonEncode(data),
      "recreate_sign": 0
    };
    EasyLoading.show();
    Api.kocQrcode(params).listen((event) {
      EasyLoading.dismiss();
      if (event['code'] == 0) {
        state.qrCode = event['qrcode']['qrcode_url'] ?? '';
      }
      callback.call(state.qrCode);
    }).onError((e) {
      EasyLoading.dismiss();
    });
  }

  void CopyLink() {
    var detail;
    if (state.goodsDetail != null &&
        state.goodsDetail['spec_item_detail'] != null) {
      detail = state.goodsDetail['spec_item_detail'];
    } else {
      toast("获取商品信息失败");
      return;
    }
    var url = "pages/index?mberType=2&applyerId=" +
        SpUtil.getInt('empeNumId').toString() +
        "&applyer=" +
        SpUtil.getInt('empeNumId').toString() +
        '&currentShopId=' +
        shopId;

    String urlData = '';
    if (state.typeIndex == 1) {
      urlData = url +
          '&isGopreSale=true&style_num_id=' +
          detail['style_num_id'].toString() +
          '&itemid' +
          detail['item_num_id'].toString();
    } else {
      urlData = url +
          '&isGoGoodDetail=true&style_num_id=' +
          detail['style_num_id'].toString();
    }

    var params = {
      "app_id": Config.MINI_APPID, //小程序的appId
      "page_url": urlData, //小程序目标页面url+参数
      "page_title": '商品详情' //小程序目标页面标题
    };
    print('复制链接');
    print(urlData);

    Api.generateshortlink(params).listen((event) async {

      if (event['code'] == 0) {
        Clipboard.setData(ClipboardData(text: event['link']));
        toast("复制成功");
      } else {
        toast("系统错误，复制失败");
      }
      print(event);
    });
  }

  void sharePoster(var goodsDetail) {
    ClipboardData data =
        new ClipboardData(text: '${goodsDetail['style_name']}');
    Clipboard.setData(data);
    var params = {
      "access_token": SpUtil.getString('token'),
      "qrcode_media_type": 2,
      "qrcode_type": 5,
      "miniprogram_code": {
        "appid": Config.MINI_APPID,
        "scene": "",
        "page": "pages/index"
      },
      "related_entity_id": goodsDetail['style_num_id'], //直接放商品的style_num_id
      "user_num_id": 0, //写死
      "valid_type": 1,
      "datajson":
          "{\"isWechatShop\":1,\"mberType\":2,\"applyerId\":${SpUtil.getInt('empeNumId')},\"shopname\":\"${SpUtil.getString('empeName')}\"}",
    };
    String qrCode = '';
    Api.kocQrcode(params).listen((event) async {
      qrCode = event['qrcode']['qrcode_url'];
      var resp = await Dio()
          .get(qrCode, options: Options(responseType: ResponseType.bytes));
      await ImageGallerySaver.saveImage(Uint8List.fromList(resp.data));
      fluwx.shareToWeChat(
        WeChatShareImageModel(
          WeChatImage.network(
            qrCode,
          ),
          scene: WeChatScene.TIMELINE,
        ),
      );
    });
  }

  ///去支付
  void goTopay() {
    print('去支付');
    // print(state.goodsDetail);
    var isPreSale = state.goodsDetail['spec_item_detail']['is_pre_sale'];
    var argument = {
      'shop_id': state.goodsDetail['shop_id'],
      "item_num_id": state.goodsDetail['item_num_id'],
      "style_num_id": state.goodsDetail['style_num_id'],
      "ec_style_num_id": state.ec_style_num_id == null
          ? state.goodsDetail['spec_item_detail']['ec_style_num_id']
          : state.ec_style_num_id,
      'shopnum': state.num
    };

    if (state.ec_style_num_id != null) {
      // var itemId = "";
      var key = "${state.ec_style_num_id}";
      // print(state.goodsDetail);
      // return;
      key = state.ecStyleNumIdList.join("_");
      if (state.spec_item[key] == null) {
        toast("当前规格无货");
        return;
      }
      argument["item_num_id"] = state.spec_item[key]["item_num_id"];
    }
    print(argument);
    if (isPreSale == 1) {
      goToPreSale();
    } else {
      Get.toNamed(RouteConfig.settleAccounts, arguments: argument);
    }

    // return;
    // var params = {
    //   "usr_num_id": SpUtil.getInt('empeNumId'),
    //   'access_token': SpUtil.getString('token'),
    //   "use_platform": 2,
    //   "channel_num_id": 99,
    //
    //   "ec_shop_num_id": state.goodsDetail['shop_id'], //商品详情的店铺
    //   "item_num_id": state.goodsDetail['item_num_id'], //商品详情的商品shop_id
    //   "quantity": 1.0,
    //   "style_num_id": state.goodsDetail['style_num_id'], //商品详情的店铺
    //  "ec_style_num_id": state.goodsDetail['spec_item_detail']//       ['ec_style_num_id'], //商品详情的店铺
    //   "tran_type_num_id": 3,
    //   "is_logistics_cart": '1',
    // };
    // Api.orderNowBuy(params).listen((event) {
    //   if (event['code'] == 0) {
    //     //      Get.toNamed(RouteConfig.orderSettlement, arguments: {
    //     // }).then((value) {
    //     //   onReady();
    //     //   update();
    //     // });
    //   } else {
    //     toast('失败');
    //   }
    // });
  }

  void requestAddToFavorite() {
    if (state.favorite_sign == false) {
      var params = {
        "use_platform": 2,
        "style_num_id": styleNumId,
        // "ec_shop_num_id": SpUtil.getInt('storeShopNum')?.toString(),
        "ec_shop_num_id": shopId,
        "access_token": SpUtil.getString("token")
      };
      Api.addGoodsToFavorite(params).listen((event) {
        if (event['code'] == 0) {
          toast('加入收藏成功');
          state.favorite_sign = true;
        }
        update();
      });
    } else {
      var params = {
        'style_num_id': styleNumId,
        'ec_shop_num_id': shopId,
        'access_token': SpUtil.getString('token'),
      };
      Api.collectListsDelete(params).listen((event) {
        if (event['code'] == 0) {
          toast('取消收藏成功');
          state.favorite_sign = false;
        }
        update();
      });
    }
  }

  minusNum() {
    if (state.num <= 1.0) {
      return;
    } else {
      state.num--;
    }

    update();
  }

  // 规格选择
  specificationChoose() {
    Get.forceAppUpdate();
  }

  addNum() {
    print(state.num);
    print(state.goodsDetail['spec_item_detail']['store']);
    if (state.num >= state.goodsDetail['spec_item_detail']['store']) {
      return;
    } else {
      state.num++;
    }

    update();
  }

  Map getBottomMoney() {
    String priceStr = '', oldPriceStr = '', tiShi = '';
    bool oldBool = false;
    var _details = state.goodsDetail['spec_item_detail'];
    if (state.selectSpecObj != null && state.selectSpecObj.isNotEmpty) {
      _details = state.selectSpecObj;
    }
    if (_details['is_seckill'] == 1) {
      // 秒杀商品
      priceStr = _details['price'].toString();
      oldBool = _details['mkt_price'] > _details['price']; // 显示旧价格
      oldPriceStr = _details['mkt_price'].toString();
    } else if (_details['is_pre_sale'] == 1) {
      priceStr = _details['price'].toString();
      oldBool = _details['mkt_price'] > _details['price']; // 显示旧价格
      oldPriceStr = _details['mkt_price'].toString();
    } else {
      if (_details['expect_price'] > 0) {
        priceStr = '${_details['expect_price'].toString()}';
        tiShi = '折后';
        oldBool = _details['mkt_price'] > _details['expect_price']; // 显示旧价格
        oldPriceStr = _details['mkt_price'].toString();
      } else {
        priceStr = _details['price'].toString();
        oldBool = _details['mkt_price'] > _details['price']; // 显示旧价格
        oldPriceStr = _details['mkt_price'].toString(); //market_price
      }
    }
    if (state.specificationParametersList.length > 0) {
      // String price = state
      //     .specificationParameters[state.ec_style_num_id.toString()]["price"]
      //     .toString();
      String key = state.ecStyleNumIdList.join("_");
      var data = state.spec_item[key];
      String price = "0";

      if (data != null) {
        price = data['price'].toString();
      }
      print("specificationParameters====${state.ec_style_num_id.toString()}");
      return {'priceStr': price, 'oldPriceStr': oldPriceStr};
    }
    print(">>>>>>>ecStyleNumIdList=${state.ecStyleNumIdList}");
    return {'priceStr': priceStr, 'oldPriceStr': oldPriceStr};
  }

  void goToThirdShop() {
    SpUtil.remove(Config.GET_SHOP_INFO);
    SpUtil.putObject(Config.GET_SHOP_INFO, state.shopInfos);
    SpUtil.putInt(Config.IS_CHANGE_SHOP,
        SpUtil.getInt('storeShopNum').toString() == shopId ? 0 : 1);
    Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
  }

  void getAndGoThirdShop() {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString('token'),
      "ec_shop_num_id": shopId,
    };
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          var shoplistes = event['ec_shop_infos'];
          state.shopInfos = {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          };
          update();
        }
      } else {
        toast(event['massage']);
      }
    });
  }

  void goToPreSale() {
    if (SpUtil.getString('token') == null ||
        SpUtil.getString('token').isEmpty) {
      Get.toNamed(RouteConfig.mallLogin, arguments: {
        'itemNumId': itemNumId,
        'styleNumId': styleNumId,
        'shopId': shopId,
        'typeIndex': state.typeIndex,
      }).then((value) {
        if (SpUtil.getString('token') != null &&
            SpUtil.getString('token').isNotEmpty) {
          requestDetail();
        }
      });
    } else {
      print(
          '====== 立即预定 ====== 点击事件！！！！${state.goodsDetail['spec_item_detail']}');
      Get.toNamed(RouteConfig.preSaleActiveOrder, arguments: {
        'shop_id': state.goodsDetail['shop_id'],
        "item_num_id": state.goodsDetail['item_num_id'],
        "style_num_id": state.goodsDetail['style_num_id'],
        "ec_style_num_id": state.goodsDetail['spec_item_detail']
            ['ec_style_num_id'],
        'shopnum': state.num,
        "ecactivity_id": state.goodsDetail['spec_item_detail']
            ['activity_num_id'],
        "typeIndex": state.typeIndex,
      }).then((value) {
        if (value != null) {
          getCurrentLocationInfo(success: (data) {
            var addressAllString = data['addressAllString'];
            var addressInfo = data['addressInfo'];
            state.addressAllString = addressAllString;
            state.addressInfo = addressInfo;
            changeSelectAddress(addressInfo);
            requestDetail();
          });
        }
      });
    }
  }

  // 分享朋友圈
  void shareToWechatCircle() {
    var detail;
    if (state.goodsDetail != null &&
        state.goodsDetail['spec_item_detail'] != null) {
      detail = state.goodsDetail['spec_item_detail'];
    } else {
      return;
    }
    print('---------------分享朋友圈--------------------');
    print(detail);
    // 处理发布到朋友圈
    if (detail['image_default_id'] == null ||
        detail['image_default_id'] == "") {
      toast("分享失败，未获取到图片地址");
      return;
    }
    print('是否是预售');
    print(detail);
    var data;
    if (state.typeIndex == 1) {
      data = Config.H5_URL +
          '&isGopreSale=true&style_num_id=' +
          detail['style_num_id'].toString() +
          '&itemid' +
          detail['item_num_id'].toString()+'&currentShopId='+state.shopInfos['shop_id'].toString();
    } else {
      data = Config.H5_URL +
          '&isGoGoodDetail=true&style_num_id=' +
          detail['style_num_id'].toString()+'&currentShopId='+state.shopInfos['shop_id'].toString();
    }

    // var data = Config.WEB_URL +
    //     'goods_detail?itemNumId=${detail['item_num_id']}&applyer=${SpUtil.getInt('empeNumId')}&styleNumId=${detail['style_num_id']}&shopId=$shopId&typeIndex=${detail['is_pre_sale'] ?? 0}';
    // print('朋友圈分享链接: $data');
    var model = fluwx.WeChatShareWebPageModel(
      data,
      description: detail['item_name'],
      title: detail['item_name'],
      thumbnail: fluwx.WeChatImage.network(detail['image_default_id']),
      scene: fluwx.WeChatScene.TIMELINE,
    );
    fluwx.shareToWeChat(model);
  }

  // 分享朋友圈
  void shareToFriend1() {
    var detail;
    if (state.goodsDetail != null &&
        state.goodsDetail['spec_item_detail'] != null) {
      detail = state.goodsDetail['spec_item_detail'];
    } else {
      return;
    }
    // 处理发布到朋友圈
    if (detail['image_default_id'] == null ||
        detail['image_default_id'] == "") {
      toast("分享失败，未获取到图片地址");
      return;
    }
    var data;
    if (state.typeIndex == 1) {
      data = Config.H5_URL +
          '&isGopreSale=true&style_num_id=' +
          detail['style_num_id'].toString() +
          '&itemid' +
          detail['item_num_id'].toString();
    } else {
      data = Config.H5_URL +
          '&isGoGoodDetail=true&style_num_id=' +
          detail['style_num_id'].toString();
    }
    print('朋友圈分享链接: $data');
    var model = fluwx.WeChatShareWebPageModel(
      data,
      description: detail['item_name'],
      title: detail['item_name'],
      thumbnail: fluwx.WeChatImage.network(detail['image_default_id']),
      scene: fluwx.WeChatScene.SESSION,
    );
    fluwx.shareToWeChat(model);
  }

  // bool visibles = false;
  //
  // getConsume() {
  //   var params = {
  //     "channel_num_id": 99,
  //     "sub_unit_num_id": 102002,
  //     // "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
  //     "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
  //     "award_types": null,
  //     'access_token': SpUtil.getString('token'),
  //   };
  //   Api.taskQuery(params).listen((event) {
  //     if (event['code'] == 0) {
  //       setState(() {
  //         if (event['member_surprise_task_infos'] != null &&
  //             event['member_surprise_task_infos'].length > 0) {
  //           event['member_surprise_task_infos'].forEach((element) {
  //             if (element['member_task_infos'] != null &&
  //                 element['member_task_infos'].length > 0 &&
  //                 element['award_type'] == 606) {
  //               var data = element['member_task_infos'][0];
  //               rule['label'] = data['award_type_name'];
  //               rule['actName'] = data['award_type_name'];
  //               rule['actTime'][0] = data['begin_dtme'];
  //               rule['actTime'][1] = data['end_dtme'];
  //               rule['platform'] =
  //                   getTaskScreen(data['member_task_rule']['platform'])
  //                       .toString();
  //               rule['giftTime'] = data['member_task_rule']['award_date_info'];
  //               rule['actRule'] = data['member_task_rule']['award_rule'];
  //             }
  //           });
  //         }
  //         visibles = true;
  //       });
  //     }
  //   });
  // }

  getConsume() async {
    var params = {
      "channel_num_id": 99,
      "sub_unit_num_id":
          SpUtil.getObject(Config.GET_SHOP_INFO)['sub_unit_num_id'], // 102002,
      // "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "award_types": null,
      'access_token': SpUtil.getString('token'),
    };
    Api.taskQuery(params).listen((event) {
      if (event['code'] == 0) {
        print('taskQuery event result :$event');
        //  state.SurprisetaskVisible=true;
        if (event['member_surprise_task_infos'] != null &&
            event['member_surprise_task_infos'].length > 0) {
          event['member_surprise_task_infos'].forEach((element) {
            if (element['member_task_infos'] != null &&
                element['member_task_infos'].length > 0 &&
                element['award_type'] == 606) {
              state.SurprisetaskVisible = true;
              element['member_task_infos'].forEach((elements) {
                var data = elements;
                data['name'] = element['award_type_name'];
                state.ConsumeList.add(data);
              });
            }
          });
        }
      }
      update();
    });
  }

  setCurrentSpec() {
    if (state.ecStyleNumIdList.length == 0) {
      return;
    }
    String key = state.ecStyleNumIdList.join("_");
    var data = state.spec_item[key];
    state.specName = data['item_name'];
    // update();
  }
}
